package controller;

import model.User;
import model.UserDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserDAO userDAO = new UserDAO();
        User user = new User();
        user.setName(username);
        user.setPassword(password);
        user.setGroup_id(1); // 默认分组为1

        boolean isUserAdded = userDAO.addUser(user);

        try (PrintWriter out = response.getWriter()) {
            if (isUserAdded) {
                out.print("{\"message\": \"注册成功\"}");
            } else {
//                500 服务器错误
                response.setStatus(500);
                out.print("{\"message\": \"注册失败，请重试\"}");
            }
            out.flush();
        }
    }
}
